// import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { createLogger } from './common';

const logger = createLogger('http');
type IRequest = Request & { _parsedUrl: any };
export const LoggerMiddleware = (
  req: IRequest,
  res: Response,
  next: NextFunction,
) => {
  // 健康检查
  if (req.url == '/health') {
    res.send('ok');
    next();
    return;
  }
  const start = Date.now();
  res.on('finish', () => {
    const end = Date.now();
    const duration = end - start;
    const method = req.method.toLowerCase();
    process.nextTick(() => {
      let data: any = '';
      if (method == 'get') {
        data = `query=>${JSON.stringify(req._parsedUrl)}`;
      } else if (method == 'post') {
        data = `body=>${JSON.stringify(req.body)}`;
      }
      if (res.statusCode >= 500) {
        logger.error(
          `----请求日志------method=>${method},duration=>${duration}ms;header=>${req.rawHeaders};params=>${JSON.stringify(req.params)}----${data}----`,
          req.url,
        );
      } else if (res.statusCode >= 400) {
        logger.warn(
          `----请求日志------method=>${method},duration=>${duration}ms;header=>${req.rawHeaders};params=>${JSON.stringify(req.params)}-----${data}---`,
          req.url,
        );
      } else {
        logger.debug(
          `----请求日志------method=>${method},duration=>${duration}ms;header=>${req.rawHeaders};params=>${JSON.stringify(req.params)}-----${data}---`,
          req.url,
        );
      }
    });
  });
  next();
};
